import React from 'react';
import $ from 'webpack-zepto';
import Config from '../../common/config.js';
import Util from '../../common/util.js';
import Loader from '../../common/loader.js';

var scope;
export default class SellerForm extends React.Component {

    initState() {
        return {
            src: "",
            isShow: false,
            upProof: {
                data: '',
                number: '',
                date: '',
                doc: ''
            },
            showDialog: false,
            title: '',
            content: '',
            terminal: {},
            limitDialog: false,
            numDialog: false
        };
    };

    constructor(props) {
        super(props);
        this.state = this.initState();
        scope = this;
    }

    upload() {
        return scope.state.limitDialog == false ? scope.uploadFalse() : scope.uploadTrue()
    }

    uploadFalse() {
        return (
            <div className="weui_cells weui_cells_form upload">
                <div className="weui_cell">
                    <div className="weui_cell_bd weui_cell_primary">
                        <div className="weui_uploader">
                            <div className="weui_uploader_hd weui_cell">
                                <div className="weui_cell_bd weui_cell_primary uploadText">销售凭证上传</div>
                                <div className="weui_cell_ft limit-mes">上传图片请限制在5M以内</div>
                            </div>
                            <div className="weui_uploader_bd">
                                <div className="weui_uploader_input_wrp">
                                    <input className="weui_uploader_input" name="photo"
                                           onChange={scope.handleInputValue.bind(this,'doc')}
                                           ref="doc"
                                           capture="camera"
                                           type="file" accept="image/*" runat="server" id="doc"/>
                                </div>
                                <ul className="weui_uploader_files">
                                    <li className="weui_uploader_file" ref='preview'>
                                        <img id="preview" className={'update-img'+(scope.state.isShow?' ':' hide')}
                                             src={'http://'+scope.state.src} alt=""/>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    uploadTrue() {
        return (
            <div className="weui_cells weui_cells_form upload">
                <div className="weui_cell">
                    <div className="weui_cell_bd weui_cell_primary">
                        <div className="weui_uploader">
                            <div className="weui_uploader_hd weui_cell">
                                <div className="weui_cell_bd weui_cell_primary uploadText">销售凭证上传</div>
                                <div className="weui_cell_ft limit-mes">上传图片请限制在5M以内</div>
                            </div>
                            <div className="weui_uploader_bd">
                                <div className="weui_uploader_input_wrp">
                                    <div class="act">
                                        <input type="hidden" name={scope.state.act} value={scope.state.proof}/>
                                    </div>
                                    <input className="weui_uploader_input" name="photo"
                                           onChange={scope.handleInputValue.bind(this,'doc')}
                                           ref="doc"
                                           capture="camera"
                                           type="file" accept="image/*" runat="server" id="doc"/>
                                </div>
                                <ul className="weui_uploader_files">
                                    <li className="weui_uploader_file" ref='preview'>
                                        <img id="preview" className={'update-img'+(scope.state.isShow?' ':' hide')}
                                             src={'http://'+scope.state.src} alt=""/>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                {scope.dialog()}
            </div>
        )
    }

    goods() {
        let goodsInfo = [];
        let terminal = {};
        $.ajax({
                url: Config.path('terminal', ['?appid=' + this.props.appId, '&uToken=' + Util.storage().get(this.props.appId), '&act=getGoods']),
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (resp) {
                    if (resp.status == 401) {
                        //window.location.href = 'index.html?appid=' + scope.props.appId;

                    } else {
                        terminal = resp.data.terminal;
                        goodsInfo = resp.data.goods;
                    }
                }
            }
        );
        return (
            <div className="goods">
                {scope.goodsInfo(goodsInfo)}
                {scope.goodsNum(goodsInfo)}
                {scope.dealer(terminal)}
                {scope.salesman(terminal)}
                {scope.saleTime()}
            </div>
        )
    }

    goodsInfo(goodsInfo) {
        let goods = goodsInfo.map(function (obj) {
            return (
                <option value={obj.goods_id}>{obj.gc_name + ' ' + obj.spec_desc}</option>
            )
        });
        return (
            <div className="weui_cell weui_cell_select weui_select_after">
                <div className="weui_cell_hd">
                    <label for="" className="weui_label">商品信息</label>
                </div>
                <div className="weui_cell_bd weui_cell_primary">
                    <select className="weui_select" name="goods_id"
                            ref="data"
                            onChange={scope.handleInputValue.bind(this,'data')}>
                        <option value=''>选择销售商品</option>
                        {goods}
                    </select>
                </div>
            </div>
        )
    }

    goodsNum(goodsInfo) {
        return scope.state.numDialog == false ? scope.goodsNumFalse(goodsInfo) : scope.goodsNumTrue(goodsInfo);
    }

    goodsNumFalse(goodsInfo) {
        return (
            <div className="weui_cell">
                <div className="weui_cell_hd"><label className="weui_label">商品数量</label></div>
                <div className="weui_cell_bd weui_cell_primary">
                    <input className="weui_input" type="number"
                           onChange={scope.handleInputValue.bind(this,'number',goodsInfo)}
                           onBlur={scope.handleInputNumber.bind(this,'number')}
                           ref="number"
                           name="goods_num" pattern="[0-9]*" placeholder=""/>
                </div>
            </div>
        )
    }

    goodsNumTrue(goodsInfo) {
        return (
            <div className="weui_cell">
                <div className="weui_cell_hd"><label className="weui_label">商品数量</label></div>
                <div className="weui_cell_bd weui_cell_primary">
                    <input className="weui_input" type="number"
                           onChange={scope.handleInputValue.bind(this,'number',goodsInfo)}
                           ref="number"
                           name="goods_num" pattern="[0-9]*" placeholder=""/>
                </div>
                {scope.dialog()}
            </div>
        )
    }

    dealer(terminal) {
        return (
            <div className="weui_cell">
                <div className="weui_cell_hd"><label className="weui_label">经销商</label></div>
                <div className="weui_cell_bd weui_cell_primary">
                    <input className="weui_input" name="dealer"
                           value={terminal.terminal_name}
                           ref="dealer"
                           readonly="readonly"
                           onChange={scope.handleInputValue.bind(this,'dealer')}
                           type="text" placeholder=""/>
                </div>
            </div>
        )
    }

    salesman(terminal) {
        return (
            <div className="weui_cell">
                <div className="weui_cell_hd"><label className="weui_label">销售员</label></div>
                <div className="weui_cell_bd weui_cell_primary">
                    <input className="weui_input" name="salesman"
                           value={terminal.terminal_contact}
                           ref="salesman"
                           readonly="readonly"
                           onChange={scope.handleInputValue.bind(this,'salesman')}
                           type="text" placeholder=""/>
                </div>
            </div>
        )
    }

    saleTime() {
        return (
            <div className="weui_cell">
                <div className="weui_cell_hd"><label for="" className="weui_label">时间</label></div>
                <div className="weui_cell_bd weui_cell_primary">
                    <input className="weui_input" name="saleTime" type="date"
                           ref="date"
                           onChange={scope.handleInputValue.bind(this,'date')}
                           placeholder=""/>
                </div>
            </div>
        )
    }

    subBtn() {
        return scope.state.showDialog == false?scope.upSuccess():scope.upErr();
    }

    upSuccess(){
        return (
            <div className="weui_btn_area sub-btn">
                <a className="weui_btn weui_btn_plain_default" id="showDialog2" onClick={scope.upData}>上传</a>
            </div>
        )
    }

    upErr(){
        return (
            <div className="weui_btn_area sub-btn">
                <a className="weui_btn weui_btn_plain_default" id="showDialog2" onClick={scope.upData}>上传</a>
                {scope.dialog()}
            </div>
        )
    }

    dialog() {
        return (
            <div className="weui_dialog_alert" id="dialog2">
                <div className="weui_mask"></div>
                <div className="weui_dialog">
                    <div className="weui_dialog_hd"><strong class="weui_dialog_title">{scope.state.title}</strong></div>
                    <div className="weui_dialog_bd">{scope.state.content}</div>
                    <div className="weui_dialog_ft">
                        <a href="javascript:;" className="weui_btn_dialog primary" onClick={scope.closeDialog}>确定</a>
                    </div>
                </div>
            </div>
        )
    }

    closeDialog() {
        scope.setState({
            showDialog: false,
            limitDialog: false,
            title: '',
            content: '',
            numDialog: false
        })
    }

    render() {
        return (
            <form className="seller-form" id="uploadForm">
                {scope.upload()}
                {scope.goods()}
                {scope.subBtn()}
            </form>
        )
    }

    handleInputNumber() {
        if (scope.refs.number.value <= 0) {
            scope.setState({
                showDialog: true,
                title: '填写的商品数量有误',
                content: '请正确填写商品数量'
            });
        }
    }

    handleInputValue(key) {
        let upProof = scope.state.upProof;
        upProof[key] = scope.refs[key].value;
        if (key == 'number') {
            scope.refs[key].value = parseInt(scope.refs[key].value);
            upProof[key] = scope.refs[key].value
        }
        scope.setState({upProof: upProof});
        if (key == 'doc') {
            let fileSize = scope.refs[key].files[0].size;
            let limitSize = 5 * 1024 * 1024;
            if (fileSize > limitSize) {
                scope.setState({
                    limitDialog: true,
                    title: '超出图片限制',
                    content: '请上传图片限制在5M以内'
                });
            } else {
                let formData = new FormData($("#uploadForm")[0]);
                formData.append('act', 'proof');
                $.ajax({
                    url: Config.path('terminal', ['?appid=' + scope.props.appId, '&uToken=' + Util.storage().get(scope.props.appId)]),
                    type: 'post',
                    dataType: 'json',
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    async: false,
                    success: function (resp) {
                        scope.setState({
                            src: resp.data,
                            isShow: true
                        })
                    }
                })
            }
        }
    }

    upData() {
         if (!scope.state.upProof.data) {
            scope.setState({
                showDialog: true,
                title: '未填写商品信息',
                content: '请填写商品信息'
            })
        } else if (!scope.state.upProof.number) {
            scope.setState({
                showDialog: true,
                title: '未填写商品数量',
                content: '请填写商品数量'
            })
        } else if (!scope.state.upProof.date) {
            scope.setState({
                showDialog: true,
                title: '未填写销售日期',
                content: '请选择销售日期'
            })
        } else {
            let formData = new FormData($("#uploadForm")[0]);
            $.ajax({
                type: 'post',
                url: Config.path('terminal', ['?appid=' + scope.props.appId, '&uToken=' + Util.storage().get(scope.props.appId)]),
                dataType: 'json',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                async: false,
                beforeSend: function () {
                    Loader.start();
                },
                success: function (resp) {
                    console.log(resp)
                    if (resp.status == 200) {
                        window.location.href = 'seller.html?appid=' + scope.props.appId + '&uToken=' + Util.storage().get(scope.props.appId)
                    } else if (resp.status == 401) {
                        //window.location.href = 'index.html?appid=' + scope.props.appId;
                    } else if (resp.status == 503 && resp.err == 'balance not enough') {
                        scope.setState({
                            title: '数量输入错误',
                            content: '请修改商品数量',
                            numDialog: true
                        })
                    }
                    Loader.end();
                }
            })
        }
    }
}
